package info.niwota.webime.gae;

import info.niwota.gae.ContentServlet;

import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class MainServlet extends ContentServlet {
	private static final Logger log = Logger.getLogger(MainServlet.class
			.getName());

	protected boolean handle(HttpServletRequest req, HttpServletResponse resp)
		throws Exception {
		String uri = req.getRequestURI();

		log.finest("method: "+ req.getMethod()+ " uri: " + uri + "?" + req.getQueryString());
		
		UserService userService = UserServiceFactory.getUserService();
		boolean loggedIn = userService.isUserLoggedIn();
		User user = userService.getCurrentUser();
		String peer = req.getParameter("peer");
		
		if (user == null && peer == null ) {
			sendLogin(req, resp);
			return true;
		}
		
		//master only for now
		JSONObject data = new JSONObject();
		String username = (user == null ? "" : user.getEmail());
		peer = (peer == null ? user.getEmail() : peer);
		
		boolean isAdmin = (loggedIn && userService.isUserAdmin());
		
		data.put("peer", peer);
		data.put("authenticated", loggedIn);
		data.put("user", username);
		data.put("admin", isAdmin);
		//
		req.setAttribute("user", user);
		req.setAttribute("data", data.toString());
		req.setAttribute("loggedIn", loggedIn);
		
		req.setAttribute("user", user);
		req.setAttribute("data", data.toString());
		req.setAttribute("loggedIn", loggedIn);
		
		resp.setContentType("text/html");
		req.getRequestDispatcher("/WEB-INF/main.jsp").forward(req, resp);
		return true;

	}
}
